package com.baitiaojun.gateway.config;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.fastjson.JSONObject;
import com.baitiaojun.api.vo.JsonRes;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;

/**
 * @类名 SentinelConfig
 * @描述 流控降级处理
 * @作者 白条君
 * @创建日期 2023/1/11 15:26
 * @版本 1.0
 */
@Configuration
public class SentinelConfig {

    @PostConstruct
    public void init() {
        GatewayCallbackManager.setBlockHandler((exchange, t) -> {
            JsonRes jsonRes = JsonRes.builder().error(HttpStatus.BAD_GATEWAY.value(), "网关异常");
            return ServerResponse.ok().body(Mono.just(JSONObject.toJSONString(jsonRes)), String.class);
        });
    }
}
